package com.yiidata.presto.clickhouse;

import com.facebook.airlift.configuration.ConfigBinder;
import com.facebook.presto.plugin.jdbc.BaseJdbcConfig;
import com.facebook.presto.plugin.jdbc.ConnectionFactory;
import com.facebook.presto.plugin.jdbc.DriverConnectionFactory;
import com.facebook.presto.plugin.jdbc.JdbcClient;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import com.google.inject.Singleton;
import ru.yandex.clickhouse.ClickHouseDriver;

import java.sql.Driver;
import java.sql.SQLException;
import java.util.Optional;
import java.util.Properties;

public class ClickhouseClientModule implements Module {
  public void configure(Binder binder) {
    binder.bind(JdbcClient.class).to(ClickhouseClient.class).in(Scopes.SINGLETON);
    ConfigBinder.configBinder(binder).bindConfig(BaseJdbcConfig.class);
    ConfigBinder.configBinder(binder).bindConfig(ClickhouseConfig.class);
  }
  
  @Provides
  @Singleton
  public static ConnectionFactory connectionFactory(BaseJdbcConfig config, ClickhouseConfig clickhouseConfig) throws SQLException {
    Properties connectionProperties = new Properties();
    return (ConnectionFactory)new DriverConnectionFactory((Driver)new ClickHouseDriver(),
            config.getConnectionUrl(),
            Optional.ofNullable(config.getUserCredentialName()),
            Optional.ofNullable(config.getPasswordCredentialName()),
            connectionProperties);
  }
}
